<?php

/**
 * +----------------------------------------------------------------------
 * | 润憬商城系统 [ 高性价比的通用商城系统 ]
 * +----------------------------------------------------------------------
 * | Copyright (c) 2022~2023 https: *www.honc.fun All rights reserved.
 * +----------------------------------------------------------------------
 * | Licensed 这不是一个自由软件，不允许对程序代码以任何形式任何目的的再发行
 * +----------------------------------------------------------------------
 * | Author: 润憬科技 Hon(陈烁临) <2275604210@qq.com>
 * +----------------------------------------------------------------------
 */

declare(strict_types=1);

namespace app\store\service;

use Shopwwi\WebmanFilesystem\Storage as WebmanFilesystemStorage;

class Storage extends WebmanFilesystemStorage
{
  public function __construct(array $config)
  {
    $this->config = config('plugin.shopwwi.filesystem.app');
    $this->mergeDbConfig($config);
    $this->adapterType = $this->config['default'] ?? 'local';
    $this->size = $this->config['max_size'] ?? 1024 * 1024 * 10;
    $this->extYes = $this->config['ext_yes'] ?? [];
    $this->extNo = $this->config['ext_no'] ?? [];
    if (!empty(static::$maker)) {
      foreach (static::$maker as $maker) {
        \call_user_func($maker, $this);
      }
    }
  }

  protected function mergeDbConfig(array $config)
  {
    $this->config['default'] = $config['default'];
    $this->config['default'] = $this->config['default'] != 'local' ? $config['default'] : 'public';
    $this->config['domain'] = null;
    if (!in_array($config['default'], ['local', 'public'])) {
      $storageCnf = $this->config['storage'][$config['default']];
      $dbCnf = data_get($config['storage'], $config['default']);
      if ($dbCnf) {
        $this->config['storage'][$config['default']] = array_merge($storageCnf, $dbCnf);
      }
      $this->config['domain'] = data_get($this->config['storage'][$config['default']], 'domain');
    }
  }

  public function getSaveFileInfo($uploadResult): array
  {
    // 自动生成的文件名称
    //     {#76
    //   +"adapter": "local"
    //   +"origin_name": "5db428a8d3ab0.png"
    //   +"file_name": "storage/67f3eea26115033b7f6ffc78465f58ef_64aedb679c6bb.png"
    //   +"storage_key": "67f3eea26115033b7f6ffc78465f58ef_64aedb679c6bb"
    //   +"file_url": "//127.0.0.1:8787/storage/67f3eea26115033b7f6ffc78465f58ef_64aedb679c6bb.png"
    //   +"size": 1100
    //   +"mime_type": "image/png"
    //   +"extension": "png"
    //   +"file_height": 48
    //   +"file_width": 48
    // }
    return [
      'storage' => $uploadResult->adapter,                 // 存储方式
      'domain' => $this->config['domain'] ?? '',   // 存储域名
      'file_path' => $uploadResult->file_name,                    // 文件路径
      'file_name' => $uploadResult->origin_name,                    // 文件名称
      'file_size' => $uploadResult->size,       // 文件大小(字节)
      'file_ext' => $uploadResult->extension,                      // 文件扩展名
    ];
  }
}
